package io.github.shang11925.sbvuewelearn.service.impl;

import io.github.shang11925.sbvuewelearn.dao.VideoAttachmentsRepository;
import io.github.shang11925.sbvuewelearn.dto.VideoAttachmentsDTO;
import io.github.shang11925.sbvuewelearn.entity.VideoAttachments;
import io.github.shang11925.sbvuewelearn.service.VideoAttachmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class VideoAttachmentsServiceImpl implements VideoAttachmentsService {
    @Autowired
    VideoAttachmentsRepository videoAttachmentsRepository;

    @Value("${custom.upload.base-path}")
    String uploadBasePath;
    @Value("${custom.upload.videoAtt-path}")
    String videoAttachmentsPath;

    @Override
    public List<VideoAttachments> findBySectionId(Long sectionId) {
        return videoAttachmentsRepository.findBySectionId(sectionId);
    }

    @Override
    public void add(VideoAttachmentsDTO videoAttachmentsDTO) {
        VideoAttachments videoAttachments = new VideoAttachments();
        videoAttachments.setAttachmentId(videoAttachmentsDTO.getAttachment_id());
        videoAttachments.setFileName(videoAttachmentsDTO.getFile_name());
        videoAttachments.setSectionId(videoAttachmentsDTO.getSection_id());
        videoAttachments.setFileUrl(videoAttachmentsDTO.getFile_url());

        videoAttachmentsRepository.save(videoAttachments);
    }

    @Override
    public void uploadCover(MultipartFile file, VideoAttachmentsDTO videoAttachmentsDTO) throws IOException {
        if (file != null && !file.isEmpty()) {
            File dir = new File(uploadBasePath + File.separator + videoAttachmentsPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID() + suffix;

            file.transferTo(new File(dir.getAbsolutePath() + File.separator + newFilename));
            videoAttachmentsDTO.setFile_url("/" + videoAttachmentsPath + File.separator + newFilename);
        }
    }
}
